/**
 * @name random
 * 随机商店
 */

/**
 * @name rows
 * @param int id 商店ID
 * @result：ttl-剩余自动刷新时间（S）,rows：商品列表
 * @tip 读取【shop】配置
 * 商品列表
 */
exports.rows = function () {
    let id = this.get('id', 'int');
    if (!id) {
        return this.error('args empty');
    }
    let shopConfig = this.config('shop', id);
    if (!shopConfig) {
        return this.error('config_not_exist', 'shop', id);
    }
    if (shopConfig.shopType != 2) {
        return this.error('shop_type_error', 'shop', id);
    }
    this.shop = this.model.redis('shop', this.sid);
    return this.shop.get(this.uid, id).then(ret => {
        if (!ret) {
            return refShopGoods.call(this, shopConfig);
        }
        else {
            return this.shop.ttl(this.uid, id).then(ttl => ({ "ttl": ttl, "rows": ret }))
        }
    })
}

/**
 * @name buy
 * @param int id 商品ID(随机商城配置ID)
 * @param int siteID 商品ID(随机商城配置ID)
 * @param int num 购买数量
 * 购买商品
 */
exports.buy = function () {
    let shopID = this.get('id', 'int');
    let siteID = this.get('siteID', 'int');
    let num = this.get('num', 'int') || 1;
    if (!shopID || !siteID || num < 1) {
        return this.error('args empty');
    }

    let shopRandomItems = this.config('shopRandomItems', shopID);
    if (!shopRandomItems) {
        return this.error('config_not_exist', 'shopRandomItems', shopID);
    }
    siteID = siteID - 1;
    let id = shopID;//shopRandomItems["type"];
    let shop = this.model.redis('shop', this.sid);
    let itemConfig = shopRandomItems.Coll[siteID];
    return shop.get(this.uid, id, 0).then(ret => {
        if (itemConfig["limitTimes"] != 0) {
            if (ret[siteID] < num) {
                return this.error('shop_num_limit', id);
            }
        }
        this.updater.sub(itemConfig['costId'], itemConfig['costNum'] * num);
        this.updater.add(itemConfig['itemId'], itemConfig['itemNum'] * num);
        this.updater.record.add(43, num);
        this.updater.daily.add("record.43", num);
        // return;
        // for( let sub of shopRandomItems["sub"] ){
        //     this.updater.sub(sub['id'],sub['num']*num );
        // }
        // for( let add of shopRandomItems["item"] ){
        //     this.updater.add(add['id'],add['num']*num );
        // }
        // return this.library.call(this.updater,'shop/limit',itemConfig['limitTimes']);
        // }).then(r => {
        return this.updater.save();
    }).then(r => {
        // return shop.set(this.uid,id,siteID,num);
        return shop.incr(this.uid, id, siteID, -1 * num);
    })
}


/**
 * @name refresh
 * @param int id 商店ID
 * @tip 读取【shop】配置
 * 手动刷新
 */
exports.refresh = function () {
    let id = this.get('id', 'int');
    if (!id) {
        return this.error('args empty');
    }
    let shopConfig = this.config('shop', id);
    if (!shopConfig || shopConfig['refreshTimes'] == 0) {
        return this.error('config_not_exist', 'shopRandomType', id);
    }
    let dkey = ["shop", 'refresh', id].join(".");
    this.shop = this.model.redis('shop', this.sid);
    this.updater.daily.add(dkey, 1);
    return this.updater.data().then(r => {
        // //每日刷新次数判断
        // let dval = this.updater.daily.get(dkey)||0;
        // if( dval >= shopConfig['refresh']){
        //     return this.error("shop_refresh_limit",dval , shopRandomType['refresh'])
        // }
        // let rkey = id * 1000 + dval+1;
        // let shopRandomRefresh = this.config('shopRandomRefresh',rkey);
        // if(!shopRandomRefresh ){
        //     return this.error('config_not_exist','shopRandomRefresh',rkey);
        // }

        // for( let sub of shopRandomRefresh["sub"] ){
        //     this.updater.sub(sub['id'],sub['num'] );
        // }
        // return this.library.call(this.updater,'shop/limit',shopRandomRefresh['limit']);
        this.updater.sub(shopConfig['refreshItem'], shopConfig['refreshCount']);
        return this.updater.save()
        // return ;
    }).then(r => {
        return refShopGoods.call(this, shopConfig);
    })
    // .then(r=>{
    //     return this.updater.save()
    // })
}



//商店刷新
function refShopGoods(config) {
    let id = config["shopId"];
    let Relative = this.library("random").Relative;
    // let shopRandomItems = this.config.search('shopRandomItems','type',id);
    let shopRandomItems = this.config('shopRandomItems', id);
    if (!shopRandomItems) {
        return this.error("config_not_exist", 'shopRandomItems', id)
    }
    let goodsGroup = {}, goodsResult = {};
    for (let v of shopRandomItems.Coll) {
        let k = v['id'];
        // let bag = v["bag"];
        // if(!goodsGroup[bag]) {
        //     goodsGroup[bag] = {};
        // }
        // goodsGroup[bag][k] = v;
        goodsGroup[k] = { "rate": v["rate"] };
    }
    for (let i = 0; i < config["itemCount"]; i++) {
        let v = Relative(goodsGroup, "rate");
        // console.log(v);
        if (v !== false) {
            //goodsMaxNum.call(this,goodsGroup[k][v]['max']);
            goodsResult[v] = shopRandomItems.Coll[v - 1]["limitTimes"];
            delete goodsGroup[v];
            // delete goodsGroup[v];
        }
    }
    // for(let k in goodsGroup){
    //     let v = Relative(goodsGroup,"rate");
    //     if(v!==false){
    //         //goodsMaxNum.call(this,goodsGroup[k][v]['max']);
    //         goodsResult[v] = {"buyTimes":0};
    //     }
    // }
    if (Object.keys(goodsResult).length < 1) {
        return this.error('shop_refresh_empty', id);
    }
    let expire = config["expire"];
    return this.shop.del(this.uid, id).then(r => {
        return this.shop.set(this.uid, id, goodsResult);
    }).then(r => {
        return this.shop.expire(this.uid, id, expire);
    }).then(r => {
        return { "ttl": expire, "rows": goodsResult };
    })
}


function goodsMaxNum(arr) {
    if (!arr[1]) {
        return arr[0] || 1;
    }
    else {
        return this.library("random/Roll", arr[0], arr[1]);
    }
}


